package com.situ.mall.listener;

import com.situ.mall.constant.MqConstant;
import com.situ.mall.pojo.entity.Orders;
import com.situ.mall.service.IOrdersService;
import com.situ.mall.util.MultiDelayMessage;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class OrderStatusListener {
    @Autowired
    private IOrdersService ordersService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(MqConstant.DELAY_ORDER_QUEUE),
            exchange = @Exchange(name = MqConstant.DELAY_EXCHANGE, delayed = "true"),
            key = MqConstant.DELAY_ORDER_ROUTING_KEY
    ))
    public void listenDelayMessage(MultiDelayMessage<Long> msg) {
        System.out.println("OrderStatusListener.listenDelayMessage");
        //1.获取消息中的订单id
        Long orderNo = msg.getData();
        //2.查询订单，判断状态
        Orders orders = ordersService.getById(orderNo);
        //订单不存在或者订单已经支付 订单状态:0-已取消-1-未付款，2-已付款，3-已发货，4-交易成功，5-交易关闭
        if (orders == null || orders.getStatus() > 1) {
            return;
        }

        //3.订单未支付，判断是否还有剩余的延时时间
        if (msg.hasNextDelay()) {
            List<Long> delayMillis = msg.getDelayMillis();
            System.out.println(delayMillis);
            //有延时时间，需要重发延时消息
            Long delay = msg.removeNextDelay();
            rabbitTemplate.convertAndSend(MqConstant.DELAY_EXCHANGE, MqConstant.DELAY_ORDER_ROUTING_KEY, msg, new MessagePostProcessor() {
                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    message.getMessageProperties().setDelay(Math.toIntExact(delay));
                    return message;
                }
            });
            return;
        } else {
            //4.没有延时时间，说明订单超时30分钟未支付
            ordersService.cancelOrder(orderNo);
        }
    }
}
